﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel.Configuration;
using System.Configuration;
using System.ServiceModel;
using System.Timers;
using System.Reflection;
using Components;
using ServiceHelper;
using Microsoft.Win32;
using System.ServiceProcess;

namespace ControlService
{
    public partial class FrmService : Form
    {
        string keyVal = Application.StartupPath + "\\" + "k.dat";

        public FrmService(bool start)
        {
            InitializeComponent();

            try
            {
                //启动数据库服务
                ServiceController myService = new ServiceController(ConfigurationManager.AppSettings["s"]);
                if (myService.Status != ServiceControllerStatus.Running)
                {
                    myService.Start();
                }

            }
            catch
            {
                MessageBox.Show("请检查配置文件中的数据库服务配置节错误，可能无法启动数据库服务，请修正！", "提示");
                return;
            }

            //加载是否重系统启动的复选框
            string status = CommonUtil.GetInstance.LoadFromFile(keyVal);
            this.checkBox1.Checked = "Y" == status;

            //查看当前服务的状态
            ServiceHost m_serviceHost = new ServiceHost(typeof(CommonContract));
            if (m_serviceHost.State == CommunicationState.Opened) tspStatus1.Text = "服务已经启动";

            if (start)
            {
                button1_Click(null, null);
                this.Hide();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ServiceHost aServiceHost = null;
            Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

            foreach (ServiceElement el in svcmod.Services.Services)
            {
                Type svcType = Type.GetType(el.Name + "," + el.Name.Split('.')[0]);

                if (svcType == null)

                    throw new Exception("Invalid Service Type " + el.Name + " in configuration file.");

                aServiceHost = new ServiceHost(svcType);

                aServiceHost.Opened += delegate
                {
                    tspStatus1.Text = "服务已经启动";
                };

                try
                {
                    aServiceHost.Open();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("服务已经启动！");
                    Application.Exit();
                    return;
                }
            }


            Run(); //启动定时器
        }

        private static void Run()
        {
            System.Timers.Timer time = new System.Timers.Timer();
            time.Interval = 1000 * 60 * 1; //默认是1分钟 (测试)
            time.Elapsed += new ElapsedEventHandler(CallbackGuid);//启动定时器
            time.Enabled = true;
            time.Start();//启动定时器
        }

        /// <summary>
        /// 定期回收服务器的GUID
        /// </summary>
        private static void CallbackGuid(object source, ElapsedEventArgs e)
        {
            Context.Callback(Global.SESSION_OUT_TIME); //过期时间设置成三分钟
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ServiceHost aServiceHost = null;

            Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);

            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");

            foreach (ServiceElement el in svcmod.Services.Services)
            {
                Type svcType = Type.GetType(el.Name + "," + el.Name.Split('.')[0]);

                if (svcType == null) continue;

                aServiceHost = new ServiceHost(svcType);

                aServiceHost.Closed += delegate
                {
                    tspStatus1.Text = "服务器已停止";
                };

                aServiceHost.Close();
            }
        }


        /// <summary>
        /// 开机启动项
        /// </summary>
        /// <param name="Started">是否启动</param>
        /// <param name="name">启动值的名称</param>
        /// <param name="path">启动程序的路径</param>
        public static void RunWhenStart(bool Started, string name, string path)
        {
            RegistryKey HKLM = Registry.LocalMachine;
            RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            if (Started == true)
            {
                try
                {
                    Run.SetValue(name, path);
                    HKLM.Close();
                }
                catch (Exception Err)
                {
                    //MessageBox.Show(Err.Message.ToString(), "MUS", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    Run.DeleteValue(name);
                    HKLM.Close();
                }
                catch (Exception)
                {
                    //
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            CommonUtil.GetInstance.SaveToFileOverride(keyVal, checkBox1.Checked ? "Y" : "N");

            RunWhenStart(checkBox1.Checked, "VDSERVER", Application.ExecutablePath + " -l");
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
    }
}
